package com.chase.framerwork.dao;

import java.util.Date;

import com.chase.framerwork.exception.SysException;
import com.chase.framerwork.util.DateUtil;
import com.chase.framerwork.util.StringUtil;

/**
 * 
 * SQL,拼接sql使用,使用效果和hql相似
 * 
 * @Author Chase
 * @Date 2013-10-23
 */
public class SQL
{
	/**
	 * 参数表达式
	 */
	public static String PARAM_EXPRESSION = "\\$\\{[\\w}]+}";

	/**
	 * 包含参数表达式的sql语句
	 */
	public static String STATMENT = "^.*(\\$\\{[\\w}]+}).*$";

	/**
	 * SQL本身对象,用于返回，提供链式操作
	 */
	private static SQL sql;

	/**
	 * SQL语句缓冲区
	 */
	private StringBuffer sqlBuffer;

	/**
	 * 私有构造方法,不提供new操作
	 */
	private SQL()
	{
		sqlBuffer = new StringBuffer();
	}

	/**
	 * 创建执行的Sql语句
	 * 
	 * @param initSql
	 * @return
	 */
	public static final SQL createSql(String initSql)
	{
		if (sql == null)
		{
			sql = new SQL();
		}

		sql.append(initSql);

		return sql;
	}

	/**
	 * 创建sql语句
	 * 
	 * @return
	 */
	public static final SQL createSql()
	{
		return createSql("");
	}

	/**
	 * 追加sql语句
	 * 
	 * @param sqlParagraph
	 * @return
	 */
	public SQL append(String sqlParagraph)
	{
		sqlBuffer.append(sqlParagraph).append(" ");

		return sql;
	}

	public SQL append(String sqlParagraph, Object param)
	{

		if (!StringUtil.validate(STATMENT, sqlParagraph))
		{
			throw new SysException("The Sql:[" + sqlParagraph + "] Not include param expression of ${...} ");
		}

		sql.append(sqlParagraph.replaceFirst(PARAM_EXPRESSION, "'" + param.toString()) + "'");

		return sql;
	}

	public StringBuffer getSql()
	{
		return sqlBuffer;
	}

	public void setSql(StringBuffer sql)
	{
		this.sqlBuffer = sql;
	}

	@Override
	public String toString()
	{
		return "sql = [" + sqlBuffer + "]";
	}

	public static void main(String[] args)
	{
		SQL sql = SQL.createSql("select * from sys_user where 1=1");
		sql.append("and status = ${status}", 1);
		sql.append("and createDate = ${createDate}", DateUtil.formateDate(new Date()));
		sql.append("order by createDate desc");

		System.out.println(sql.toString());
	}
}
